<template>
  <view>
    <up-avatar :src="avatar" size="48rpx" :default-url="defaultUrl" shape="square" @click="uploadImg"></up-avatar>
  </view>
</template>

<script setup>
  import {
    ref,
    defineProps,
    defineEmits
  } from 'vue'
  import {onShow} from '@dcloudio/uni-app'
  import {
    env
  } from '@/http/env.js'
  const {
    src,
    defaultUrl
  } = defineProps(['src', 'defaultUrl'])
  const emit = defineEmits(['UploadAvatar'])
  const avatar = ref('')
  onShow(()=>{
    avatar.value = src
  })
  //  上传头像
  const uploadFilePromise = (url) => {
    const token = uni.getStorageSync('userInfo').token
    uni.showToast({
      title: '上传中',
      icon: 'loading'
    })
    return new Promise((resolve, reject) => {
      let a = uni.uploadFile({
        url: `${env.baseUrl}/common/upload`, //测试地址
        // url: 'https://localhost:8080/common/upload', //测试环境
        filePath: url,
        name: 'file',
        formData: {
          user: 'test'
        },
        header: {
          token: token
        },
        success: (res) => {
          const data = JSON.parse(res.data)
          if (data && data.code === 1) {
            resolve(data.data)
            avatar.value = data.data.fullurl
            emit("UploadAvatar", data.data.fullurl)
          } else {
            uni.showToast({
              title: data.msg,
              icon: "none"
            })
          }
        },
        fail(err) {
          uni.showToast({
            title: err.errMsg,
            icon: 'none'
          })
        }
      });
    })
  }
  //选取图片
  const uploadImg = () => {
    uni.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      success: function(res) {
        uploadFilePromise(res.tempFilePaths[0])
      }
    });
  }
</script>

<style lang="less">

</style>